<?php

namespace app\controller;

use app\model\User;
use support\Cache;
use support\Response;
use support\Request;
use Tinywan\Jwt\JwtToken;


/**
 * 基础控制器
 */
class Base
{
    protected Request $request;

    protected int $user_id;
    protected User $user;

    public function __construct()
    {
        $this->request = request();

        //获取控制器名称
        $controller = $this->request->controller;
        $notCheckToken = ['app\controller\LoginController', 'app\controller\IndexController'];
        if (in_array($controller, $notCheckToken)) {
            return;
        }
        //解析token
        $this->user_id = JwtToken::getCurrentId();

    }


    /**
     * API基类初始化
     */
    public function initialize()
    {
    }

    /**
     * 返回格式化json数据
     *
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return Response
     */
    protected function resJson(int $code, string $msg = 'ok', array $data = []): Response
    {
        return json(['code' => $code, 'msg' => $msg, 'data' => $data, 'current_time' => date('Y-m-d H:i:s')]);
    }

    protected function success(string $msg = '成功', array $data = []): Response
    {
        return $this->resJson(1, $msg, $data);
    }

    protected function fail(string $msg = '失败', array $data = []): Response
    {
        return $this->resJson(0, $msg, $data);
    }

    protected function json(array $data = []): Response
    {
        $data['current_time'] = date('Y-m-d H:i:s');
        return json($data);
    }

    //处理模型数据 去除多余字段
    public function handleModelData(\app\model\Base $model_data, $field = ['created_at', 'updated_at', 'deleted_at']): \app\model\Base
    {
        return $model_data->hidden($field);
    }


}
